package pswvclass.pswvandroid2.com;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.user.FindAccountPassword;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HttpUtils;
import pswvclass.pswvandroid2.com.util.payment.AuthResult;
import pswvclass.pswvandroid2.com.util.payment.H5PayDemoActivity;
import pswvclass.pswvandroid2.com.util.payment.OrderInfoUtil2_0;
import pswvclass.pswvandroid2.com.util.payment.PayDemoActivity;
import pswvclass.pswvandroid2.com.util.payment.PayResult;

/**
 */
public class Login extends AppCompatActivity implements View.OnClickListener {
    private String tag = "Login";
    private TextView user_account;
    private TextView user_password;
    private Button login_user;
    private Button register_user;
    private Button forget_password_user;
    private int userId;
    protected static final int LOGIN_SUCCESS = 0;
    protected static final int REGISTER_SUCCESS = 2;
    protected static final int ERROR = 1;
    private DBHelper db;
    private SQLiteDatabase sd;

    @Override
    protected void onCreate(Bundle bundle) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(bundle);
        setContentView(R.layout.login);
        db = new DBHelper(this);
        try {
            sd = db.getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
            Log.v("", e + "");
        }
        user_account = (TextView) findViewById(R.id.user_account);
        user_password = (TextView) findViewById(R.id.user_password);
        login_user = (Button) findViewById(R.id.login_user);
        login_user.setOnClickListener(this);
        register_user = (Button) findViewById(R.id.register_user);
        register_user.setOnClickListener(this);
        forget_password_user = (Button) findViewById(R.id.forget_password_user);
        forget_password_user.setOnClickListener(this);
        //Cursor cursor=UserPerfect.query("user", null, null, null, null, null, null);
       /* 删除
         UserPerfect.delete("user", " account= ?", new String[] { "e" });*/
        Cursor cursor = sd.rawQuery("select * from user", null);
        if (cursor.getCount() != 0) {
            int state = 0;
            Cursor cursor1 = sd.query("user", new String[]{DBHelper.STATE, DBHelper.USERID}, null, null, null, null, null);
            while (cursor1.moveToNext()) {
                if (cursor1.getInt(cursor1.getColumnIndex("state")) == 1) {
                    Message msg = Message.obtain();
                    msg.what = LOGIN_SUCCESS;
                    mHandler.sendMessage(msg);
                    return;
                }
            }
            cursor.close();
            cursor1.close();
        }
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOGIN_SUCCESS:
                    Intent intent = new Intent();
                    intent.setClass(Login.this, PswvActivity.class);
                    startActivity(intent);
                    break;
                case ERROR:

                    break;
                default:
                    break;
            }

        }

        ;

    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_user: {
                final String account = user_account.getText().toString().trim();
                final String password = user_password.getText().toString().trim();

                if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {
                    Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/loginAction/login";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("account", account);
                            map1.put("password", password);
                            //data2 = hu.submitPostData(src);
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            userId = jsonObj.getJSONObject("response").getInt("userId");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                //继续修改
                                Cursor cursor1 = sd.query("user", null, "userId=?", new String[]{userId + ""}, null, null, null);
                                if (cursor1.getCount() != 0) {
                                    ContentValues values1 = new ContentValues();
                                    values1.put(DBHelper.STATE, 1);
                                    sd.update("user", values1, "userId=?", new String[]{userId + ""});
                                    Message msg = Message.obtain();
                                    msg.what = LOGIN_SUCCESS;
                                    mHandler.sendMessage(msg);
                                    cursor1.close();
                                } else {
                                    ContentValues values = new ContentValues();
                                    values.put(DBHelper.USERID, userId);
                                    values.put(DBHelper.ACCOUNT, account);
                                    values.put(DBHelper.PASSWORD, password);
                                    values.put(DBHelper.STATE, 1);
                                    sd.insert(DBHelper.TABLE_NAME, null, values);
                                    Message msg = Message.obtain();
                                    msg.what = LOGIN_SUCCESS;
                                    mHandler.sendMessage(msg);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                            Log.v(tag, e + "");
                        }
                    }
                }.start();
                break;
            }
            case R.id.register_user: {
                Intent intent = new Intent();
                intent.setClass(Login.this, Register.class);
                startActivity(intent);
                break;
            }
            case R.id.forget_password_user: {
                Intent intent = new Intent();
                intent.setClass(Login.this, FindAccountPassword.class);
                startActivity(intent);
                break;
            }
            default:
                break;
        }
    }
}
